<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .wrapper{
            position: relative;
            margin: 150px auto;
            width: 300px;
            height: 300px;
            border: 10px solid orange;
        }
        .wrapper .box{
            position: absolute;
            left: 0;
            top: 0;
            width: 80px;
            height: 80px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="box"></div>
    </div>

    <script>
        var wrapper = document.querySelector('.wrapper');
        var box = document.querySelector('.box');
        var wrapperOffsetTop = wrapper.offsetTop;
        var wrapperOffsetLeft = wrapper.offsetLeft;
        var wrapperWidth = wrapper.offsetWidth;
        var wrapperHeight = wrapper.offsetHeight;
        var boxWidth = box.offsetWidth;
        var boxHeight = box.offsetHeight;

        box.onmousedown = function (e) {
            var startX = e.offsetX;
            var startY = e.offsetY;

            document.onmousemove = function (e) {
                var pageX = e.pageX;
                var pageY = e.pageY;
                // 上下左右四临界
                var leftV = startX + 10 + wrapperOffsetLeft;
                var rightV = wrapperWidth + wrapperOffsetLeft - 10 -(boxWidth - startX);
                var topV = startY + 10 + wrapperOffsetTop;
                var bottomV = wrapperHeight + wrapperOffsetTop - 10 - (boxHeight - startY);
                // 设置一般情况下盒子位置
                var left = pageX - wrapperOffsetLeft - 10 - startX + 'px';
                var top = pageY - wrapperOffsetTop - 10 - startY + 'px';
                // 小于左临界
                if ( pageX < leftV ) {
                    left = 0;
                }
                // 大于右临界
                if ( pageX > rightV ) {
                    left = wrapperWidth - 20 - boxWidth + 'px';
                }
                // 小于上临界
                if (pageY < topV) {
                    top = 0;
                }
                // 大于下临界
                if (pageY > bottomV) {
                    top = wrapperHeight - 20 - boxHeight + 'px';
                }

                box.style.left = left;
                box.style.top = top;
            }
            document.onmouseup = function () {
                document.onmousemove = null;
            }
        }
    </script>
</body>

</html>